<template>
  <div class="table-container">
    <el-card>
      <template #header>
        <div class="card-header">用户数据表格</div>
      </template>
      
      <el-row style="margin-bottom: 15px;">
        <el-col :span="8">
          <!-- 新增 el-form 容器 -->
          <el-form inline>
            <el-form-item label="用户名" style="margin-bottom: 0">
              <el-input 
                v-model="searchKey" 
                placeholder="请输入用户名搜索" 
                suffix-icon="el-icon-search"
                @keyup.enter.native="fetchData">
                <el-button slot="append" @click="fetchData">搜索</el-button>
              </el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="16" style="text-align: right;">
          <el-button type="primary" @click="handleCreate">新增用户</el-button>
        </el-col>
      </el-row>
      
      <el-table 
        :data="tableData" 
        stripe 
        border
        @row-click="handleRowClick">
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="gender" label="性别">
          <template slot-scope="scope">
            {{ scope.row.gender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="用户信息">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="formData.gender">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="formData.age" type="number"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchKey: '',
      
      // 对话框相关
      dialogVisible: false,
      dialogType: 'create', // 'create' 或 'edit'
      formData: {
        id: null,
        username: '',
        email: '',
        gender: 1,
        age: 18
      },
      
      // 表单验证规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          { type: 'number', message: '年龄必须为数字', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.$axios.get('/api/users', {
        params: {
          page: this.currentPage - 1,
          pageSize: this.pageSize,
          keyword: this.searchKey
        }
      })
      .then(response => {
        this.tableData = response.data.items || [];
        this.total = response.data.total || 0;
      })
      .catch(error => {
        this.$message.error('获取数据失败');
      });
    },
    
    // 新增用户
    handleCreate() {
      this.dialogType = 'create';
      this.formData = {
        username: '',
        email: '',
        gender: 1,
        age: 18
      };
      this.dialogVisible = true;
    },
    
    // 编辑用户
    handleEdit(row) {
      this.dialogType = 'edit';
      // 复制对象，避免直接修改原数据
      this.formData = { ...row };
      this.dialogVisible = true;
    },
    
    // 提交表单
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.dialogType === 'create') {
            // 新增用户
            this.$axios.post('/api/users', this.formData)
              .then(() => {
                this.$message.success('新增成功');
                this.dialogVisible = false;
                this.fetchData(); // 刷新数据
              })
              .catch(error => {
                console.error('新增失败:', error);
                this.$message.error('新增失败');
              });
          } else {
            // 编辑用户
            this.$axios.patch(`/api/users/${this.formData.id}`, this.formData)
              .then(() => {
                this.$message.success('修改成功');
                this.dialogVisible = false;
                this.fetchData(); // 刷新数据
              })
              .catch(error => {
                console.error('修改失败:', error);
                this.$message.error('修改失败');
              });
          }
        } else {
          return false;
        }
      });
    },
    
    // 其他方法保持不变
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    handleDelete(row) {
      this.$confirm('确定要删除此用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete(`/api/users/${row.id}`)
          .then(() => {
            this.$message.success('删除成功');
            this.fetchData();
          })
          .catch(() => {
            this.$message.error('删除失败');
          });
      }).catch(() => {
        // 取消操作
      });
    },
    handleRowClick(row) {
      // this.$message.info(`点击了用户: ${row.username}`);
      console.log(`点击了用户: ${row.username}`)
    }
  }
}
</script>

<style scoped>
.table-container {
  padding: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

/* 使用/deep/或::v-deep穿透scoped样式 */
.custom-table/deep/.el-table__cell {
  font-weight: bold;
}
</style>